package com.example.common.utils;

import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Component
public class HttpUtil {
    
    private static final RestTemplate restTemplate = new RestTemplate();
    
    /**
     * 发送GET请求
     */
    public static String get(String url) {
        return restTemplate.getForObject(url, String.class);
    }
    
    /**
     * 发送GET请求，带参数
     */
    public static String get(String url, Map<String, ?> params) {
        return restTemplate.getForObject(url, String.class, params);
    }
    
    /**
     * 发送POST请求（带JSON请求体）
     */
    public static String postJson(String url, Object body) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<>(body, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
        return response.getBody();
    }
    
    /**
     * 发送POST请求，带自定义header
     */
    public static String postJson(String url, Object body, Map<String, String> headersMap) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headersMap.forEach(headers::set);
        HttpEntity<Object> entity = new HttpEntity<>(body, headers);
        return restTemplate.postForObject(url, entity, String.class);
    }
    
    /**
     * 发送DELETE请求
     */
    public static void delete(String url) {
        restTemplate.delete(url);
    }
    
    /**
     * 发送PUT请求（带JSON请求体）
     */
    public static void putJson(String url, Object body) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<>(body, headers);
        restTemplate.put(url, entity);
    }
}
